package org.akomantoso.core.io.util;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.PrefaceoptElement;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.util.group.BlockElementsGroup;
import org.akomantoso.core.io.util.group.PrefaceContainersGroup;
import org.akomantoso.core.util.MapUtil;

/**
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 */
public final class PrefaceoptElementUtil {

	// PrefaceOptElement

	private PrefaceoptElementUtil() {
	}

	public static final Map<String, Instantiator<PrefaceoptElement>> MAP;

	public static void read(Input in,List<PrefaceoptElement> elements) throws IOException {
		final String localName = in.getLocalName();
		in.readNext();
		
		PrefaceoptElement element = null;
		while(true) {
			switch (in.getEventType()) {
			case InputConstants.START_ELEMENT:
				elements.add(element = instantiate(in.getLocalName()));
				element.readExternal(in);
				break;			
			case InputConstants.END_ELEMENT:
				if (localName.equals( in.getLocalName())) {
					return;
				} 
			}
			in.readNext();
		}
	}
	
	private static PrefaceoptElement instantiate(String elementName) {

		final Instantiator<? extends PrefaceoptElement> instatiator = MAP.get(elementName);
		if (instatiator == null) {
			throw new RuntimeException("Tag [" + elementName + "] not supported PrefaceOptElement ?!?");
		}
		return instatiator.instantiate();
	}

	static {
		Map<String, Instantiator<PrefaceoptElement>> temp = new HashMap<String, Instantiator<PrefaceoptElement>>();
		MapUtil.copy(BlockElementsGroup.MAP, temp);
		MapUtil.copy(PrefaceContainersGroup.MAP, temp);
		MAP = Collections.unmodifiableMap(temp);
	}
	
}